import { Component, OnInit, OnDestroy, Inject, ViewChild, TemplateRef } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { NzMessageService, NzModalService } from 'ng-zorro-antd'
import * as dayjs from 'dayjs'
import { ACLService } from '@delon/acl'

import { DetailBaseClass } from '@shared/classes/DetailBaseClass'
import { Merchant } from '@shared/interfaces/merchant'
import { PageService } from '@shared/services/page.service'
import { MerchantService } from '../merchant.service'
import { IDetailHeaderTab } from '@shared/interfaces/common'
import { DataService } from '@shared/services/data.service'
import { PageScrollService } from 'ngx-page-scroll-core'
import { DOCUMENT } from '@angular/platform-browser'
import { ETabScrollStatus } from '@shared/enums'
import { StatusTextMap } from '@shared/interfaces/common'
import { DetailHeaderComponent } from '@shared/components/detail-header/detail-header.component'
import { CommonMerchantService } from '@shared/services/merchant.service'
import { Validators } from 'app/utils/validator'
import {
  emailReg,
  merNameENReg,
  merNameMaxLength,
  merNameENMaxLength,
  contactNameMaxLength,
  emailMaxLength,
} from 'app/utils/contraints'
import { ModalService } from '@shared/services/modal.service'
import { I18NService } from '@core'

@Component({
  selector: 'app-merchant-detail',
  templateUrl: './detail.component.html',
  styles: [],
})
export class MerchantDetailComponent extends DetailBaseClass<Merchant> implements OnInit, OnDestroy {
  @ViewChild('tpStatus') tpStatus: TemplateRef<any>
  @ViewChild('tpControl') tpControl: TemplateRef<any>
  @ViewChild(DetailHeaderComponent) detailHeaderComponent: DetailHeaderComponent

  imgSrc = 'assets/images/centaur/base-info-pic/merchant.png'
  STATUS = {
    FREEZE: 'freeze',
    NORMAL: 'normal',
  }
  tabs: IDetailHeaderTab[] = [
    { text: this.trans('MENU.BIZ.STORES'), url: './stores' },
    { text: this.trans('GENERAL.INFO.OTHER.SYSTEM_INFO'), url: './systems' },
    // Phrase two
    // { text: this.trans('GENERAL.INFO.OTHER.SETTLEMENT'), url: './settlements' },
    { text: this.trans('GENERAL.INFO.OTHER.TRADE_INFO'), url: './trades' },
    { text: this.trans('GENERAL.INFO.OTHER.USERS'), url: './users' },
  ]

  routerSubscriber: any

  constructor(
    private route: ActivatedRoute,
    private merchantService: MerchantService,
    private commonMerchantService: CommonMerchantService,
    private msg: NzMessageService,
    private dataService: DataService,
    private pageScrollService: PageScrollService,
    private modal: NzModalService,
    public pageService: PageService,
    private modalService: ModalService,
    public aclService: ACLService,
    private i18n: I18NService,
    @Inject(DOCUMENT) private document: any,
  ) {
    super(pageService)
  }

  ngOnInit() {
    this.loading = false

    this.id = this.route.snapshot.params['id']

    this.initial()

    this.getData()

    this.pageService.tabScrollStatus$.subscribe(tabStatus => {
      this.pageScroll(ETabScrollStatus.InitialLoad)
    })
  }

  ngOnDestroy() {
    this.pageService.triggerBaseEdit(false)
    this.pageService.setTabScrollStatus(ETabScrollStatus.InitialLoad)
  }

  getData(): void {
    this.merchantService.getOne(this.id).subscribe(merchant => {
      this.dataService.setMerchant(merchant)
      this.commonMerchantService.setViewingMerchant(merchant)
      this.detailData = merchant
      this.initColumns()
      this.loading = false
    })
  }

  initial() {
    this.firstColumns = [
      {
        span: 8,
        index: 'common.merNum',
        label: 'GENERAL.MERCHANT.NUM',
        labelI18n: 'GENERAL.MERCHANT.NUM',
        disEditable: true,
      },
      {
        span: 8,
        index: 'common.merName',
        label: 'GENERAL.MERCHANT.NAME',
        labelI18n: 'GENERAL.MERCHANT.NAME',
        validator: {
          funcs: [Validators.required, Validators.maxLength(merNameMaxLength)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.MERCHANT.NAME') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: merNameMaxLength }),
          ],
        },
      },
      {
        span: 8,
        index: 'common.merNameEN',
        label: 'GENERAL.MERCHANT.NAME_EN',
        labelI18n: 'GENERAL.MERCHANT.NAME_EN',
        validator: {
          funcs: [Validators.required, Validators.maxLength(merNameENMaxLength), Validators.pattern(merNameENReg)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.MERCHANT.NAME_EN') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: merNameENMaxLength }),
            this.trans('VALIDATION.PATTERN.ALPHANUMERIC_SYMBOLS_ONLY'),
          ],
        },
      },
    ]
    this.secondColumns = [
      {
        span: 8,
        index: 'common.contact.name',
        label: 'GENERAL.INFO.CONTACT_NAME',
        labelI18n: 'GENERAL.INFO.CONTACT_NAME',
        validator: {
          funcs: [Validators.required, Validators.maxLength(contactNameMaxLength)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.CONTACT_NAME') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: contactNameMaxLength }),
          ],
        },
      },
      {
        span: 8,
        index: 'common.contact.email',
        label: 'GENERAL.INFO.EMAIL',
        labelI18n: 'GENERAL.INFO.EMAIL',
        validator: {
          funcs: [Validators.required, Validators.maxLength(emailMaxLength), Validators.pattern(emailReg)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.EMAIL') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: emailMaxLength }),
            this.trans('VALIDATION.PATTERN.EMAIL'),
          ],
        },
      },
      {
        span: 4,
        index: 'common.status',
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        disEditable: true,
        pipe: status => this.trans(StatusTextMap[status]),
      },
      {
        span: 4,
        label: 'GENERAL.INFO.OPERATION',
        labelI18n: 'GENERAL.INFO.OPERATION',
        template: this.tpControl,
        operate: true,
        acl: ['api.put.camel.merchant.one.freeze'],
      },
    ]
  }

  triggerBaseEdit(): void {
    this.copiedDetailData = this.copyDetailData(this.detailData)
    this.pageService.triggerBaseEdit(true)
  }

  cancelBase(): void {
    this.detailData = this.copiedDetailData
    this.clearColumnsErrorTips()
    this.initColumns()
    this.pageService.triggerBaseEdit(false)
  }

  saveBase(): void {
    if (!this.checkEditValidation()) {
      this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
      return
    }
    try {
      this.detailHeaderComponent.hideButtons()
      this.pageService.triggerBaseEdit()
      this.updateColumns()
      const { intMerCode } = this.detailData.common
      this.detailData.createdAt = dayjs(this.detailData.createdAt).format()
      this.merchantService.update(intMerCode, this.detailData).subscribe(data => {
        this.detailData = data
        this.initColumns()
        this.clearColumnsErrorTips()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UPDATE_SUCCESS'))
      })
    } catch (err) {
      console.error(err)
      this.msg.error(this.trans('GENERAL.NOTIFICATION.UPDATE_FAIL'), err.message)
    }
  }

  freezeDialog(): void {
    const { merName } = this.detailData.common
    const msg = this.trans('GENERAL.NOTIFICATION.MERCHANT_FREEZE_CONFIRM', { merName })
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOK => {
      if (!isOK) return
      this.freeze()
    })
  }

  unfreezeDialog(): void {
    const { merName } = this.detailData.common
    const msg = this.trans('GENERAL.NOTIFICATION.MERCHANT_UNFREEZE_CONFIRM', { merName })
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOK => {
      if (!isOK) return
      this.unfreeze()
    })
  }

  freeze(): void {
    const { intMerCode } = this.detailData.common
    this.merchantService.freeze(intMerCode).subscribe(
      success => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
        this.getData()
      },
      () => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      },
    )
  }

  unfreeze(): void {
    const { intMerCode } = this.detailData.common
    this.merchantService.unfreeze(intMerCode).subscribe(
      success => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
        this.getData()
      },
      () => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      },
    )
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }

  private pageScroll(tabStatus: ETabScrollStatus): void {
    if (tabStatus === ETabScrollStatus.InitialLoad || tabStatus === ETabScrollStatus.Stop) {
      return
    }
    this.pageScrollService.scroll({
      document: this.document,
      scrollTarget: '.cil__scroll-div',
    })
  }
}
